<template>
  <div class="box" v-if="albumInfo.album">
    <div class="info">
      <div class="avatorMax">
        <img :src="albumInfo.album.picUrl + '?param=300y300'" alt="" />
      </div>
      <div class="right">
        <div class="title">
          <span class="type">专辑</span>
          <h3>{{ albumInfo.album.name }}</h3>
        </div>
        <div class="button">
          <div class="play" @click="playAll">
            <i class="el-icon-video-play" style="font-size: 20px"></i> 播放全部
          </div>
          <div class="collect" @click="handleSub">
            <i class="el-icon-star-off" :class="isSub ? 'isSubRed' : ''"></i>
            {{ isSub ? '已收藏' : '收藏' }}
          </div>
          <div class="share" @click="$message.warning('哦~还不能分享哦!')">
            分享
          </div>
        </div>
        <div class="tag">
          <div class="label">
            <span>歌手:</span>
            <span
              @click="
                $router.push({
                  name: 'singerDetail',
                  params: { id: albumInfo.album.artist.id }
                })
              "
              >{{ albumInfo.album.artist.name }}</span
            >
          </div>
          <div class="song">
            <span>时间: {{ albumInfo.album.publishTime | showDate }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="list" ref="list">
      <el-tabs v-model="activeId" @tab-click="handleClick">
        <el-tab-pane label="歌曲列表" name="1" class="tableBox">
          <el-table
            :data="albumInfo.songs"
            stripe
            lazy
            style="width: 100%"
            @row-dblclick="doubleClick"
            @cell-click="handelCellClick"
          >
            <el-table-column
              min-width="80"
              label="序号"
              type="index"
              :index="handleIndex"
            >
            </el-table-column>
            <el-table-column min-width="30" label="下载">
              <i class="el-icon-download"></i
            ></el-table-column>
            <el-table-column
              prop="name"
              label="标题"
              min-width="350"
            ></el-table-column>
            <el-table-column
              prop="ar[0].name"
              label="歌手"
              min-width="120"
            ></el-table-column>
            <el-table-column
              prop="al.name"
              label="专辑"
              min-width="170"
            ></el-table-column>
            <el-table-column
              prop="dt"
              label="时长"
              min-width="100"
            ></el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="评论" name="2">
          <div
            class="connmentBox"
            v-if="comments.comments"
            v-loading="isCommentLoading"
          >
            <!-- 热门评论 -->
            <comment
              v-if="comments.hotComments"
              :commentType="'album'"
              :comments="comments.hotComments"
              :commentId="albumInfo.album.id + ''"
              @getComment="handleGetComment"
              ref="hotComment"
              @handleBacktop="handleBacktop"
              ><p slot="title">精彩评论</p></comment
            >
            <!-- 最新评论 -->
            <comment
              :commentType="'album'"
              :comments="comments.comments"
              :commentId="albumInfo.album.id + ''"
              @getComment="handleGetComment"
              @handleBacktop="handleBacktop"
              :isHotComment="comments.hotComments ? false : true"
              @transToHotComment="
                (info) =>
                  this.$refs.hotComment.floorComment(
                    info.commentId,
                    info.nickName
                  )
              "
              ><p slot="title">最新评论</p></comment
            >
            <div class="pagination">
              <el-pagination
                background
                layout="prev,pager,next"
                :total="comments.total"
                :page-size="50"
                :current-page="currentCommentPage"
                @current-change="commentPageChange"
                hide-on-single-page
              >
              </el-pagination>
            </div>
            <el-backtop target=".connmentBox"></el-backtop>
          </div>
        </el-tab-pane>
        <el-tab-pane label="歌单详情" name="3">
          <p class="info">{{ albumInfo.album.description }}</p>
        </el-tab-pane>
      </el-tabs>
      <el-backtop ref="boxScroll" target=".list"></el-backtop>
    </div>
  </div>
</template>
<script>
import {
  getSingerAlbumInfo,
  getAlbumComment,
  getCollectAlbum,
  collectAlbum
} from '@/api/discover/singerDetail'
import { getMusicUrl } from '@/api/music/music'
import { handleMusicTime, handleNum, formatDate } from '@/plugins/utils'
import comment from '../musicDetail/components/comment.vue'
export default {
  data() {
    return {
      activeId: '1',
      albumInfo: {},
      comments: {},
      // 当前评论页数
      currentCommentPage: 1,
      isSub: false,
      // 评论是否在加载中
      isCommentLoading: false
    }
  },
  components: {
    comment
  },
  methods: {
    handleClick(tab) {
      if (tab.name == '2' && !this.comments.comments) {
        this.getAlbumComment()
      }
      // console.log(tab.name, event)
    },
    // 请求专辑详情-xx
    async getAlbumDetail() {
      let res = await getSingerAlbumInfo({ id: this.$route.query.id })
      res = res.data
      // 处理歌曲时间
      res.songs.forEach((item, index) => {
        res.songs[index].dt = handleMusicTime(item.dt)
      })
      console.log(res, '专辑详情')
      this.albumInfo = res
    },
    // xx-
    handleIndex(index) {
      index += 1
      if (index < 10) {
        return (index = '0' + index)
      } else {
        return index
      }
    },

    // xx-获取已收藏专辑列表并判断用户是否收藏当前专辑  因为喜欢和收藏具有较高实时性，所以每次请求都添加时间戳，避免缓存304
    async getAlbumSublist() {
      // console.log(123)
      let timestamp = Date.parse(new Date())
      let res = await getCollectAlbum({
        limit: 1000,
        timestamp
      })
      console.log(res, '已收藏专辑')
      this.$store.commit('updateSubAlbumList', res.data.data)
      console.log(this.$store.state.subAlbumList, 123123)
    },
    // 获取歌单评论-xx
    async getAlbumComment() {
      let timestamp = Date.parse(new Date())
      this.isCommentLoading = true
      const res = await getAlbumComment({
        id: this.$route.query.id,
        offset: (this.currentCommentPage - 1) * 50,
        limit: 50,
        timestamp
      })
      console.log('评论', res)
      if (res.data.code !== 200) {
        this.$message.error('获取评论失败......')
      }
      this.comments = res?.data
      this.isCommentLoading = false
    },
    // 分页页数更新-xx
    commentPageChange(page) {
      // 回到顶部
      this.handleBacktop()
      this.currentCommentPage = page
      this.getAlbumComment()
    },
    // 播放全部-xx
    async playAll() {
      // console.log(this.musicListDetail.tracks)
      this.$store.commit('updateMusicId', this.albumInfo.songs[0].id)
      this.$store.commit('updateMusicList', {
        musicList: this.albumInfo.songs,
        musicListId: this.albumInfo.album.id
      })
    },
    // 双击播放-xx
    doubleClick(row) {
      console.log(row)
      this.$store.commit('updateMusicId', row.id)
      if (this.albumInfo.album.id !== this.$store.state.musicListId) {
        this.$store.commit('updateMusicList', {
          musicList: this.albumInfo.songs,
          musicListId: this.albumInfo.album.id
        })
      }
    },
    // 收藏专辑-xx
    async handleSub() {
      if (!this.$store.state.isLogin) {
        // this.$message.error("请先进行登录操作!");
        return
      }
      this.isSub = !this.isSub
      await collectAlbum({
        id: this.$route.query.id,
        t: this.isSub ? 1 : 0
      })
      this.getAlbumSublist()
    },

    // 判断用户是否收藏了该专辑
    getIsSub() {
      this.isSub = this.$store.state.subAlbumList.find(
        (item) => item.id == this.$route.query.id
      )
    },
    // 点击下载-xx
    async handelCellClick(cell, row, column) {
      if (column?.children[0]?.children[0]?.className === 'el-icon-download') {
        // console.log('找到了')
        // this.$message.warning('敬请期待!')
        // console.log(row, cell)
        let res = await getMusicUrl(cell.id)
        // console.log(res, row, cell)
        const musicUrl = res.data.data[0].url
        // console.log(res.data.data[0].url)
        // 匹配资源的域名
        let url = res.data.data[0].url.match(/http.*?\.net/)
        // console.log(url)
        // 匹配域名名称，并匹配对应的代理
        let serve = url[0].match(/http:\/(\S*).music/)[1]
        // console.log(serve)
        // 截取后面的参数
        let params = res.data.data[0].url.slice(url[0].length)
        if (
          serve != '/m7' &&
          serve != '/m701' &&
          serve != '/m8' &&
          serve != '/m801'
        ) {
          // 没有对应的代理
          this.$message.error('匹配不到对应的代理,下载失败!')
          return
        }
        // console.log(params)
        if (musicUrl === null) {
          this.$message.warning('暂时无法获取资源')
        }
        let downloadMusicInfo = {
          url: serve + params,
          name:
            cell.name +
            ' - ' +
            cell.ar[0].name +
            '.' +
            res.data.data[0].type.toLowerCase()
        }
        // console.log(downloadMusicInfo)
        this.$store.commit('updateDownloadMusicInfo', downloadMusicInfo)
        // try {
        //   let link = document.createElement('a')
        //   link.style.display = 'none'
        //   link.href = window.URL.createObjectURL(new Blob([serve + params]))
        //   link.setAttribute(
        //     'download',
        //     cell.name +
        //       '-' +
        //       cell.ar[0].name +
        //       '.' +
        //       res.data.data[0].type.toLowerCase()
        //   )
        //   // link.download =
        //   //   cell.name +
        //   //   '-' +
        //   //   cell.ar[0].name +
        //   //   '.' +
        //   //   res.data.data[0].type.toLowerCase()
        //   document.body.appendChild(link)
        //   link.click()
        // } catch (error) {
        //   console.log(error)
        // }
      }
    },
    // 发布后的回调-xx
    handleGetComment() {
      this.getAlbumComment()
    },
    // 点击评论的评论回到置顶-xx
    handleBacktop() {
      const dom = document.querySelector('.connmentBox')
      dom.querySelector('.el-backtop').click()
    }
  },
  // async created() {
  //   await this.getAlbumDetail() // 专辑详情
  // },
  async mounted() {
    await this.getAlbumDetail() // 专辑详情
    if (this.$store.state.subAlbumList == null) {
      await this.getAlbumSublist()
    }
    this.getIsSub()
  },
  filters: {
    showDate(value) {
      // 1、先将时间戳转成Date对象
      const date = new Date(value)

      // 2、将date进行格式化
      return formatDate(date, 'yyyy-MM-dd')
    },
    handleNum
  }
}
</script>
<style lang="scss" scoped>
.box {
  padding: 0 15px 0 15px;
}

.info {
  display: flex;
  align-items: center;

  .avatorMax {
    img {
      width: 180px;
      height: 180px;
      background-color: pink;
      border-radius: 15px;
      margin-right: 15px;
    }
  }
  .right {
    .title {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      .type {
        border: 1px solid #f06e6e;
        font-size: 14px;
        color: #ec4141;
        padding: 0 2px;
        margin-right: 10px;
      }
      h3 {
        font-size: 25px;
      }
    }
    .user {
      display: flex;
      align-items: center;
      .avatorMin {
        img {
          width: 30px;
          height: 30px;
          margin-right: 8px;
          border-radius: 30px;
        }
      }
      .name {
        color: #6191c2;
        font-size: 16px;
        margin-right: 15px;
        cursor: pointer;
      }
      .time {
        font-size: 14px;
        color: #666;
      }
    }
    .button {
      display: flex;
      align-items: center;
      margin-top: 10px;
      margin-bottom: 10px;
      .play {
        background-color: #ec4141;
        color: #fff;
        font-size: 14px;
        padding: 5px 15px;
        border-radius: 15px;
        margin-right: 8px;
        cursor: pointer;
        display: flex;
        align-items: center;
        &:hover {
          background-color: #e53f3f;
        }
        .el-icon-video-play {
          margin-right: 5px;
        }
      }
      .collect,
      .share {
        border: 1px solid #ccc;
        padding: 5px 15px;
        border-radius: 15px;
        color: #666;
        font-size: 14px;
        margin-right: 8px;
        cursor: pointer;
        &:hover {
          background-color: #f7f7f7;
        }
      }
    }
    .tag {
      display: flex;
      flex-direction: column;
      font-size: 14px;
      margin-left: 30px;
      color: #666;
      .label {
        span {
          margin-right: 5px;
        }
        .tagType {
          color: #6191c2;
        }
      }
      .song {
        margin: 3px 0;
        span {
          margin-right: 5px;
        }
      }
      .intro {
        width: 800px;
        text-overflow: ellipsis;
        overflow: hidden;
        text-wrap: nowrap;
      }
    }
  }
}
.el-icon-download::before {
  font-size: 18px;
  font-weight: 700;
}
.list {
  width: 100%;
  height: 60vh;
  overflow-x: hidden;
}
// 评论返回顶部
.connmentBox {
  height: 54vh;
  overflow-x: hidden;
  // margin-bottom: 60px;
}
// 分页
.pagination {
  display: flex;
  justify-content: center;
}
// 收藏者
.collectUser {
  display: flex;
  // height: 60vh;
  flex-wrap: wrap;
  padding-left: 21px;
  margin-top: 20px;
  .songItem {
    flex: 10%;
    max-width: 130px !important;
    max-height: 130px !important;
    min-width: 130px !important;
    min-height: 130px !important;
    // border-radius: 100px;
    // overflow: hidden;
    text-align: center;
    box-sizing: border-box;
    margin-right: 12px;
    margin-bottom: 50px;
    cursor: pointer;
    // &:nth-child(9) {
    //   margin-right: 0;
    // }
  }
}
// 收藏按钮
.isSubRed {
  color: #e53f3f;
}
</style>
